package com.example.cd5160866.urlapp.view;

import android.content.Context;
import android.graphics.Color;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.util.AttributeSet;
import android.view.Gravity;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;

/**
 * @author cd5160866
 * @date 2018/10/31
 */
public class DadaIconView extends FrameLayout {
    private ImageView ivIcon;
    private TextView tvIconDesc;

    public DadaIconView(@NonNull Context context) {
        this(context, null);
    }

    public DadaIconView(@NonNull Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    public void setBubbleView(final BubbleView bubble) {
        removeView(bubble);
        if (null == bubble) {
            return;
        }
        if (ivIcon.getHeight() == 0) {
            ivIcon.post(new Runnable() {
                @Override
                public void run() {
                    setBubbleView(bubble);
                }
            });
            return;
        }

        LayoutParams bubbleParams = new LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        bubbleParams.gravity = Gravity.END | Gravity.TOP;
        int bubbleStyle = bubble.getBubbleStyle();
        int iconTopDistance = ivIcon.getTop();
        bubbleParams.topMargin = iconTopDistance - dip2px(bubbleStyle == BubbleView.STYLE_DIAN ? 2.5f : 9f);
        int iconRightDistance = ivIcon.getLeft();
        int horizontalMargin;
        if (bubbleStyle == BubbleView.STYLE_DIAN) {
            horizontalMargin = dip2px(2.5f);
        } else {
            horizontalMargin = dip2px(bubbleStyle == BubbleView.STYLE_PILL ? 21f : 9f);
        }
        bubbleParams.rightMargin = iconRightDistance - horizontalMargin;
        addView(bubble, bubbleParams);
    }

    public void setText(CharSequence text) {
        tvIconDesc.setText(text);
    }

    public ImageView getImageIcon() {
        return ivIcon;
    }

    public TextView getTextView() {
        return tvIconDesc;
    }

    private void init() {
        ivIcon = new ImageView(getContext());
        LayoutParams params = new LayoutParams(dip2px(36), dip2px(36));
        params.gravity = Gravity.CENTER;
        addView(ivIcon, params);

        tvIconDesc = new TextView(getContext());
        tvIconDesc.setTextColor(Color.parseColor("#666666"));
        tvIconDesc.setTextSize(12f);
        LayoutParams textParams = new LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        textParams.gravity = Gravity.CENTER_HORIZONTAL | Gravity.BOTTOM;
        addView(tvIconDesc, textParams);
    }

    private int dip2px(float dpValue) {
        final float scale = getContext().getResources().getDisplayMetrics().density;
        return (int) (dpValue * scale + 0.5f);
    }
}
